package com.slz.crm.server.interceptor;

import com.slz.crm.common.exiception.BaseException;
import com.slz.crm.common.exiception.ServiceException;
import com.slz.crm.common.untils.BaseUnit;
import com.slz.crm.common.untils.JwtUntil;
import com.slz.crm.pojo.ao.RoleAO;
import com.slz.crm.server.constant.MessageConstant;
import com.slz.crm.server.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Configuration
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RoleAO roleAO = new RoleAO();

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return false; // 不继续执行后续拦截器或 Controller
        }
        if (request.getRequestURI().contains("/login")){
            return true;
        }
        String token = request.getHeader(jwtProperties.getTokenName());

        if (Objects.isNull(token)){
            throw new BaseException(MessageConstant.TOKEN_IS_NULL);
        }

        try {
            Claims claims = JwtUntil.parseJWT(jwtProperties.getSecretKey(), token);

            Long roleID = claims.get("roleID",Long.class);
            Long userID = claims.get("userID",Long.class);

            roleAO.setRoleId(roleID);
            roleAO.setId(userID);

            BaseUnit.setCurrentRole(roleAO);

        } catch (Exception e) {
            throw new BaseException(MessageConstant.TOKEN_IS_ERROR);
        }


        return true;
    }
}
